package com.hn658.base.message.eventbus.handler.systemchat;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hn658.base.message.account.service.IAccountUserManagerService;
import com.hn658.base.message.common.dto.NotificationDTO;
import com.hn658.base.message.common.enums.EventType;
import com.hn658.base.message.common.enums.NotifySenderType;
import com.hn658.base.message.eventbus.event.systemchat.SystemMsgEvent;
import com.hn658.base.message.eventbus.handler.AbstractEventHandler;
import com.hn658.base.message.eventbus.util.NotifiConvert;
import com.hn658.base.message.notification.msg.entity.MessageEO;
import com.hn658.base.message.notification.notify.business.INotificationManager;
import com.hn658.base.message.notification.notify.entity.NotificationEO;
@Component
public class SystemMessageHandler extends AbstractEventHandler<SystemMsgEvent>{

	@Autowired
    private INotificationManager notificationManager;
	
	@Autowired
	private IAccountUserManagerService accountService;
	
	@Override
	public void handle(SystemMsgEvent event) {
		MessageEO msg = event.getMessage();
        NotificationEO notificationEO = NotifiConvert.convert(msg,event.getEventId());
        NotificationEO notifyDb = notificationManager.find(msg.getNotifyId());
        if(notifyDb == null){
            notificationManager.save(notificationEO);
        }else{
            notificationManager.update(notificationEO);
        }
        List<String> accountIds= new ArrayList<String>();
        //判断是否发送给个人
        if(event.getIsPerson()){
        	accountIds.add(msg.getToUid());
        }else{
        	accountIds = accountService.findAccountId(event.getAppId());        	
        }
        //查询群成员列表
    	for(String id:accountIds){
    		NotificationDTO notificationDTO = NotifiConvert.convert(msg,notificationEO);
			//判断是否正在聊天
			notificationDTO.setSenderType(NotifySenderType.Comet.getValue());
    		notificationDTO.setToUid(id);
    		notificationManager.send(notificationDTO);
    	}
	}

	@Override
	public EventType getTarget() {
		return EventType.SystemChat;
	}
	
	
}
